package cn.tedu.charging.order.utils;

import cn.tedu.charging.common.constant.XxlJobAuthConst;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

public class XxlJobTaskUtil {
    //根据传入的参数 创建一个任务

    /**
     * 专门为当前扫码下单 创建计划任务编写封装的一个http请求
     * @param restTemplate 调用者 传递一个发送请求的restTemplate
     * @param cronExpression 计划时间表达式 调用者生成计算
     * @param jobGroup 从众多执行器中,选择哪个执行分组 完成这个任务 查看order-executor的id
     * @param orderNo 任务参数 具体传递是数据 billId
     * @return
     */
    public static boolean createJobTask(RestTemplate restTemplate,String cronExpression, Integer jobGroup, String orderNo){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.set("Cookie", XxlJobAuthConst.COOKIE_NAME_VALUE);
        MultiValueMap<String, Object> formData = new LinkedMultiValueMap<>();
        formData.add("jobGroup", jobGroup); // 注意：XXL-JOB 可能需要字符串形式的数字
        formData.add("jobDesc", "订单状态检查任务");
        formData.add("author", "admin");
        formData.add("alarmEmail", "");
        formData.add("scheduleType", "CRON");
        formData.add("scheduleConf", cronExpression);
        formData.add("executorBlockStrategy", "SERIAL_EXECUTION");
        formData.add("misfireStrategy", "DO_NOTHING");
        formData.add("executorRouteStrategy", "FIRST");
        formData.add("executorHandler", "order-status-check");//@XxlJob
        formData.add("executorParam", orderNo);
        formData.add("executorTimeout", "0");
        formData.add("executorFailRetryCount", "0");
        formData.add("glueType", "BEAN");
        formData.add("glueSource", "");
        formData.add("glueRemark", "GLUE代码初始化");
        formData.add("childJobId", "");
        formData.add("triggerStatus", "1");
        formData.add("triggerLastTime", "0");
        formData.add("triggerNextTime", "0");

        String adminUrl = "http://localhost:8080/xxl-job-admin/jobinfo/add";
        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(formData, headers);
        ResponseEntity<String> response = restTemplate.exchange(
                adminUrl,
                HttpMethod.POST,
                request,
                String.class
        );
        // 4. 验证响应
        if (response.getStatusCode() == HttpStatus.OK) {
            System.out.println("延迟任务设置成功，将在2分钟后执行");
            return true;
        } else {
            System.out.println("设置失败: " + response.getBody());
            return false;
        }
    }
}
